import os, sys
from pyinotify import IN_MODIFY, WatchManager, Notifier, ThreadedNotifier, EventsCodes, ProcessEvent
import nose

class Runner(object):
	def __init__(self,*args,**kwargs):
		self.basedir = kwargs.pop('testDir')
		self.testmod = kwargs.pop('testMod')
		self.refreshrate = kwargs.pop('testRate')

	def start(self):
		manager = WatchManager()
		statuses = IN_MODIFY
		tempProcess = ChangesOnModify(self.basedir,self.testmod)	
		notifier = Notifier(manager,default_proc_fun=tempProcess)
		watchdirector = manager.add_watch(self.basedir, statuses)

		while True:
			try:
				notifier.process_events()
				if notifier.check_events():
					notifier.read_events()
			except KeyboardInterrupt:
				notifier.stop()
				print "Stopped testrunner..."
				break


class ChangesOnModify(ProcessEvent):
	def __init__(self,testdir,testpkg):
		self.testdir =  testdir
		self.testpkg =  testpkg

	def process_IN_MODIFY(self,event):
		print "Modified: %s" % os.path.join(event.path, event.name)		
		runChanges = RunAfterChanges(self.testdir,self.testpkg)
		runChanges.run()

class RunAfterChanges:
	def __init__(self,testdir,testpkg):
		self.testdir = testdir 
		self.testpkg = testpkg

	def run(self):
		testImporter = nose.importer.Importer()
		print "Test Dir --> " + self.testdir
		print "Test Pkg --> " + self.testpkg
		testImporter.importFromDir(self.testdir,self.testpkg)
		nose.run(testImporter)
		
